//
//  UICollectionViewExample.swift
//  SwiftCode
//
//  Created by yuhus on 2025/2/16.
//

import UIKit

class UICollectionViewExample: UIViewController {
  
  private lazy var collectionView: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical
    layout.minimumLineSpacing = 10
    layout.minimumInteritemSpacing = 5
    
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
    return collectionView
  }()
  
  let items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"]
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    view.addSubview(collectionView)
    collectionView.snp.makeConstraints { make in
      make.edges.equalToSuperview()
    }
  }
}

extension UICollectionViewExample :UICollectionViewDataSource {
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return items.count
  }
  
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCollectionViewCell
    cell.titleLabel.text = items[indexPath.item]
    return cell
  }
}

extension UICollectionViewExample :UICollectionViewDelegateFlowLayout {
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = collectionView.frame.width
    Timber.d("width:", width)
    if indexPath.item < 5 {
      return CGSize(width: width / 2 - 10, height: 100)
    } else {
      return CGSize(width: width - 20, height: 100)
    }
  }
}

class CustomCollectionViewCell: UICollectionViewCell {
  override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
  }
  
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupViews()
  }
  
  func setupViews() {
    // 初始化您的单元格视图
    contentView.addSubview(titleLabel)
    contentView.backgroundColor = #colorLiteral(red: 1, green: 0.4932718873, blue: 0.4739984274, alpha: 1)
    titleLabel.snp.makeConstraints { make in
      make.edges.equalToSuperview()
    }
  }
  
  lazy var titleLabel: UILabel = {
    let label = UILabel()
    label.textColor = .black
    label.textAlignment = .center
    return label
  }()
}
